package com.gscitysfy.cus.drain.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gscitysfy.cus.drain.constants.RedisKeyConstant;
import com.gscitysfy.cus.drain.modules.common.entity.DrainInspectionMnFile;
import com.gscitysfy.cus.drain.modules.common.service.IFileService;
import com.gscitysfy.cus.drain.modules.inspection.service.IDrainInspectionMnFileService;
import com.gscitysfy.cus.drain.modules.warning.entity.DrainWeatherImg;
import com.gscitysfy.cus.drain.modules.warning.service.IDrainWeatherImgService;
import com.gscitysfy.cus.drain.utils.FileUtil;
import com.gscitysfy.cus.drain.utils.SpringContextHolder;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
//
@Service
@EnableScheduling()
public class GetSatelliteImage {
    private static final Logger logger = LoggerFactory.getLogger(GetSatelliteImage.class);

    @Autowired
    IDrainWeatherImgService weatherImgService;
    @Autowired
    IDrainInspectionMnFileService drainInspectionMnFileService;
    @Resource
    private IFileService fileService;
    /**
     * 获取雷达拼图数据的请求地址
//     */
//    private static final String IMG_URL = "http://www.nmc.cn/publish/satellite/FY4A-true-color.htm";
//    /**
//     * 空白图片的访问地址
//     */
//    private static final String IMG_BLANK = "http://image.nmc.cn/static2/site/nmc/themes/basic/images/grey.gif";
    /**
     * 时间格式化
     */
    private SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Value("${local.path}")
    String path;

    @Value("${local.fileurl}")
    String fileurl;
    @Value("${wxyt.imgUrl}")
    String IMG_URL;
    @Value("${wxyt.nmcUrl}")
    String NMC_URL;

    @Value("${wxyt.imgBlank}")
    String IMG_BLANK;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Scheduled(cron = "0 0/10 * * * ?")
    public void getSatelliteImages() {


        logger.info("卫星云图定时任务开始================================================：getSatelliteImages");
//        System.getProperties().setProperty("proxySet","true");
//        System.getProperties().setProperty("http.proxyHost","172.19.0.140");
//        System.getProperties().setProperty("http.proxyPort","38808");

        try {
            if(redisTemplate.hasKey(RedisKeyConstant.REDIS_KEY_SATE_IMG_JOB)) {
                return ;
            }
            redisTemplate.opsForValue().set(RedisKeyConstant.REDIS_KEY_SATE_IMG_JOB, "10", 3, TimeUnit.MINUTES);
            logger.info("卫星云图：IMG_URL"+IMG_URL);

            Document document = Jsoup.connect(IMG_URL).get();
            List<DrainWeatherImg> imgList = getImgList(document);
            logger.info("卫星云图：imgList"+imgList.size());
            if(weatherImgService==null){
                weatherImgService= SpringContextHolder.getBean(IDrainWeatherImgService.class);
            }
            imgList.forEach(x->{
                LambdaQueryWrapper<DrainWeatherImg> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(DrainWeatherImg::getType, "weather_img_sate");
                queryWrapper.eq(DrainWeatherImg::getName, x.getName());
                if(weatherImgService.count(queryWrapper)==0){
                    weatherImgService.save(x);
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            redisTemplate.delete(RedisKeyConstant.REDIS_KEY_SATE_IMG_JOB);
        }
    }

    /**
     * 通过document对象获取里面的图片清单
     *
     * @param document document对象
     * @return 图片清单
     */
    private List<DrainWeatherImg> getImgList(Document document) {
        logger.info("1：ImgList"+document);

        List<DrainWeatherImg> list = new ArrayList<>();
        Element ul = document.getElementById("myTabContent");
        Elements elements = ul.getElementsByAttribute("data-img");
        if (null == elements || elements.isEmpty()) {
            return list;
        }
        logger.info("2：ImgList");

        Calendar calendar= Calendar.getInstance();
        calendar.setTime(new Date());
        elements.forEach(x -> {
            DrainWeatherImg item = new DrainWeatherImg();
            String url = x.attr("data-img");
            if (StringUtils.isNotBlank(url) && !url.equals(IMG_BLANK)) {
                item.setCollectTime(calendar.getTime());
                item.setFromUrl(url);
                item.setImgTime(formatDate(x.attr("data-time"), calendar));
                int endIndex = url.lastIndexOf("?");
                String imgName = url.substring(url.lastIndexOf("/") + 1, endIndex == -1 ? url.length() : endIndex);
                item.setName(imgName);
                item.setType("weather_img_sate");
                logger.info("3：ImgList");

                //上传之前判断是否存在
                LambdaQueryWrapper<DrainInspectionMnFile> queryWrapper1 = new LambdaQueryWrapper<>();
                queryWrapper1.eq(DrainInspectionMnFile::getCmFileName, imgName);
                if(drainInspectionMnFileService.count(queryWrapper1)==0) {
                    logger.info("4：ImgList");

                    try {
                        //下载之前需要将nmc的路径替换成代理的
                        if(StringUtils.isNotEmpty(NMC_URL)){
                            //非空需要替换
                            logger.info("替换url："+NMC_URL);

                            url = url.replace("image.nmc.cn",NMC_URL);
                        }
                        item.setPath(FileUtil.download(url, path + "thirds" + File.separator + "sate"
                                + File.separator + item.getName().substring(0, 8)));

                        File file =new File(item.getPath());
                        DrainInspectionMnFile commonFile = fileService.uploadFile(file);
                        item.setFileId(commonFile.getCmKid());
                        logger.info("文件id："+commonFile.getCmKid());
                        logger.info("文件url："+commonFile.getCmFilePreviewUrl());
//                    item.setUrl(commonFile.getCmFilePreviewUrl());
                        item.setUrl(fileurl + "thirds/sate/" + item.getName().substring(0,8) + "/" + imgName);
                    } catch (Exception e) {
                        e.printStackTrace();
                        item.setPath(url);
                        item.setUrl(url);
                    }
                    list.add(item);
                }

            }
        });
        return list;
    }

    private Date formatDate(String dateStr, Calendar date) {
        try{
            return dateFormat.parse(date.get(Calendar.YEAR)+"-"+dateStr.replace("/","-")+":00");
        }catch (ParseException e){
            return null;
        }
    }
}

